package com.dmz.workflow.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.echronos.commons.enums.ErrorMsgEnum;
import com.echronos.commons.exception.ParamsValidateException;
import com.dmz.workflow.constant.FormComponentConstants;
import com.dmz.workflow.constant.MsgContentEnum;
import com.dmz.workflow.constant.ProcessDefinitionConstants;
import com.dmz.workflow.dto.CommonFormComponent;
import com.dmz.workflow.dto.ProcessMessageBody;
import com.dmz.workflow.entity.FormData;
import com.dmz.workflow.entity.ProcessInstanceStatus;
import com.dmz.workflow.service.WorkflowFormDataService;
import com.dmz.workflow.service.WorkflowProcessStatusService;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.HistoryService;
import org.flowable.variable.service.impl.persistence.entity.HistoricVariableInstanceEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.LinkedHashSet;

/**
 * 流程消息体包装类
 */
@Component
public class MessageContentWrapper {

    private ProcessInstanceStatus processInstanceStatus;

    private LinkedHashSet<CommonFormComponent> formContent;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private WorkflowProcessStatusService workflowProcessStatusService;

    @Autowired
    private WorkflowFormDataService workflowFormDataService;

    private String messageContentWrapper(MsgContentEnum msgContentEnum, String... param) {
        return MessageFormat.format(msgContentEnum.content, param);
    }

    public ProcessMessageBody processMessageBodyWrapper(MsgContentEnum msgContentEnum, String starterName, String commentator) {
        ProcessMessageBody processMessageBody = new ProcessMessageBody();
        processMessageBody.setProcessInstanceId(processInstanceStatus.getProcessInstanceId());
        processMessageBody.setProcessName(processInstanceStatus.getProcessName());
        processMessageBody.setProcessStatus(processInstanceStatus.getStatus());
        processMessageBody.setFormContent(formContent);
        if (MsgContentEnum.MESSAGE_COMMENT_CONTENT.equals(msgContentEnum)) {
            processMessageBody.setContent(messageContentWrapper(msgContentEnum, commentator, starterName, processInstanceStatus.getProcessName()));
        } else if (MsgContentEnum.MESSAGE_REFUSE_COMMENT.equals(msgContentEnum) || MsgContentEnum.MESSAGE_FINISH_CONTENT.equals(msgContentEnum)) {
            processMessageBody.setContent(messageContentWrapper(msgContentEnum, processInstanceStatus.getProcessName()));
        } else {
            processMessageBody.setContent(messageContentWrapper(msgContentEnum, starterName, processInstanceStatus.getProcessName()));
        }
        return processMessageBody;
    }

    private void obtainMessageBody(String processInstanceId) {
        // 获取流程实例相关信息
        processInstanceStatus = workflowProcessStatusService.selectInstanceByInstanceId(processInstanceId);
        // 获取表单数据
        FormData formData = workflowFormDataService.selectFormDataByProcessInstanceId(processInstanceId);
        String formDataStr;
        if (ObjectUtils.isEmpty(formData)) {
            HistoricVariableInstanceEntityImpl processInstanceFormData =
                    (HistoricVariableInstanceEntityImpl) historyService.createHistoricVariableInstanceQuery()
                            .processInstanceId(processInstanceId).variableName(ProcessDefinitionConstants.PROCESS_DEFINITION_FORM_NAME).singleResult();
            formDataStr = processInstanceFormData.getTextValue();
        } else {
            formDataStr = formData.getFormData();
        }
        // 处理流程显示前三个字段的数据
        formContent = new LinkedHashSet<>();
        if (ObjectUtils.isNotEmpty(formDataStr)) {
            JSONArray jsonArray = JSONObject.parseArray(formDataStr);
            for (int i = 0; i < jsonArray.size(); i++) {
                if (formContent.size() >= 3) {
                    break;
                }
                JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
                if (String.valueOf(jsonObject.get("formKey")).contains(FormComponentConstants.ATTACHMENT_COMPONENT)
                        || String.valueOf(jsonObject.get("formKey")).contains(FormComponentConstants.MULTIPLE_SELECTION_COMPONENT)
                        || String.valueOf(jsonObject.get("formKey")).contains(FormComponentConstants.SCORE_COMPONENT)
                        || String.valueOf(jsonObject.get("formKey")).contains(FormComponentConstants.IMAGE_COMPONENT)
                        || String.valueOf(jsonObject.get("formKey")).contains(FormComponentConstants.CONTACT_COMPONENT)) {
                    continue;
                }
                if (!jsonObject.get("type").equals(FormComponentConstants.DATE_RANGE_COMPONENT)) {
                    CommonFormComponent commonFormComponent = CommonFormComponent.builder().formKey(String.valueOf(jsonObject.get("formKey")))
                            .label(String.valueOf(jsonObject.get("label"))).value(ObjectUtils.isNotEmpty(jsonObject.get("value")) ? jsonObject.get("value") : "未填写").build();
                    formContent.add(commonFormComponent);
                } else {
                    String label1 = (String) jsonObject.get("label1");
                    String label2 = (String) jsonObject.get("label2");
                    Object value1 = null;
                    Object value2 = null;
                    JSONArray valueArray = JSONObject.parseArray(jsonObject.get("value").toString());
                    if (ObjectUtils.isNotEmpty(valueArray)) {
                        value1 = valueArray.get(0);
                        value2 = valueArray.get(1);
                    }
                    CommonFormComponent commonFormComponent = CommonFormComponent.builder()
                            .formKey(String.valueOf(jsonObject.get("formKey"))).label(label1)
                            .value(ObjectUtils.isNotEmpty(value1) ? value1 : "未填写").build();
                    formContent.add(commonFormComponent);
                    if (formContent.size() <= 2) {
                        CommonFormComponent secondDateRangeValue = CommonFormComponent.builder()
                                .formKey(String.valueOf(jsonObject.get("formKey"))).label(label2)
                                .value(ObjectUtils.isNotEmpty(value2) ? value2 : "未填写").build();
                        formContent.add(secondDateRangeValue);
                    }
                }
            }
        }
    }

    public ProcessMessageBody generateNotCommentMessageBody(MsgContentEnum msgContentEnum, String processInstanceId) {
        if (StringUtils.isEmpty(processInstanceId)) {
            throw new ParamsValidateException(ErrorMsgEnum.PARAM_EMPTY.getErrorCode(), ErrorMsgEnum.PARAM_EMPTY.getMsg());
        }
        obtainMessageBody(processInstanceId);
        return processMessageBodyWrapper(msgContentEnum,
                processInstanceStatus.getMemberName(), null);
    }

    public ProcessMessageBody generateCommentMessageBody(MsgContentEnum msgContentEnum, String processInstanceId, String commentator) {
        if (StringUtils.isEmpty(processInstanceId)) {
            throw new ParamsValidateException(ErrorMsgEnum.PARAM_EMPTY.getErrorCode(), ErrorMsgEnum.PARAM_EMPTY.getMsg());
        }
        obtainMessageBody(processInstanceId);
        return processMessageBodyWrapper(msgContentEnum,
                processInstanceStatus.getMemberName(), commentator);
    }
}
